package com.oceansoft.core;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

public class CORSFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(CORSFilter.class);
    private String mWhiteList = "*";
    private boolean mIsEnableCros;
    private int mMaxAge = 3600;
    private String mAllowMethods = "POST, GET, OPTIONS, DELETE";
    private boolean mRequiredCredential = false;
    private String mAllowHeaders;

    public CORSFilter() {
    }

    public CORSFilter(boolean enableCors, List<String> whiteList, String allowHeaders, String allowMethods, boolean requiredCredential, int maxAge) {
        this.mIsEnableCros = enableCors;
        if(null != whiteList) {
            //this.mWhiteList = String.join(",", whiteList);
        }

        this.mMaxAge = maxAge;
        this.mAllowMethods = allowMethods;
        this.mRequiredCredential = requiredCredential;
        this.mAllowHeaders = allowHeaders;
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        if(this.mIsEnableCros) {
            logger.debug("CORS过滤器初始化成功，白名单:{}", this.mWhiteList);
        }

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if(this.mIsEnableCros) {
            HttpServletResponse response = (HttpServletResponse)servletResponse;
            response.setHeader("Access-Control-Allow-Origin", this.mWhiteList);
            response.setHeader("Access-Control-Allow-Methods", this.mAllowMethods);
            response.setHeader("Access-Control-Max-Age", String.valueOf(this.mMaxAge));
            if(null != this.mAllowHeaders && 0 < this.mAllowHeaders.trim().length()) {
                response.setHeader("Access-Control-Allow-Headers", this.mAllowHeaders);
            }

            if(this.mRequiredCredential) {
                response.setHeader("Access-Control-Allow-Credentials", "true");
            }
        }

        logger.debug("CrosFilter add header:{}", this.mWhiteList);
        filterChain.doFilter(servletRequest, servletResponse);
    }

    public void destroy() {
        this.mIsEnableCros = false;
        this.mWhiteList = null;
    }
}
